import React from 'react';
import {injectIntl} from './intl';
import PropTypes from 'prop-types';
import {Button, Spin, Divider, Collapse, Card, Row, Col, Table, Tabs} from 'antd';
import {hasPermissions, uuid} from './utils';
import {warrantyPolicyType, warrantyPolicyStatus} from '../Enum';
import {conventEnumValueToString, formatDateTime} from '../utils';
import {PERMISSION} from './constants';
import {PAGE, DATE_FORMAT, TABLE, DATETIME_FORMAT} from '../constants';
import routes from './routes';
import WrappedPopconfirm from '../common/WrappedPopconfirm';
import styles from './style.css';
import DescriptionList from 'ant-design-pro/lib/DescriptionList';
const {Description} = DescriptionList;
const TabPane = Tabs.TabPane;
const Panel = Collapse.Panel;
const EMPTY_ARRAY = [];
export class Detail extends React.PureComponent {
    state = {
        loading: false,
    };

    componentDidMount() {
        this.props.init();
        this.ismounted = true;
    }

    componentWillUnmount() {
        this.ismounted = false;
        this.props.onUmount();
    }

    handleAbandonClick = () => {
        this.setState({
            loading: true
        });
        this.props.onClickAbandon().then(success => {
            if(this.ismounted && !success)
                this.setState({
                    loading: false
                });
        });
    };

    handleEnableClick = () => {
        this.setState({
            loading: true
        });
        this.props.onClickEnable().then(success => {
            if(this.ismounted && !success)
                this.setState({
                    loading: false
                });
        });
    };

    renderTabs = data => {
        const vinColumns = [
            {
                title: this.props.intl.formatMessage({
                    id: 'detail.colums.vin',
                    defaultMessage: 'VIN'
                }),
                dataIndex: 'vin',
                render: (text, record, index) => {
                    const props = {};
                    if(index === record.startIndex)
                        props.rowSpan = record.rowSpan;
                    else
                        props.rowSpan = 0;
                    return {
                        children: text,
                        props
                    };
                }
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'detail.column.partCode',
                    defaultMessage: '备件编号'
                }),
                dataIndex: 'partCode',
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'detail.column.partName',
                    defaultMessage: '备件名称'
                }),
                dataIndex: 'partName',
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'detail.column.remark',
                    defaultMessage: '备注'
                }),
                dataIndex: 'remark',
            }
        ];
        const categoryColumns = [
            {
                title: this.props.intl.formatMessage({
                    id: 'detail.colums.productCategoryCode',
                    defaultMessage: '车型编号'
                }),
                dataIndex: 'productCategoryCode',
                render: (text, record, index) => {
                    const props = {};
                    if(index === record.startIndex)
                        props.rowSpan = record.rowSpan;
                    else
                        props.rowSpan = 0;
                    return {
                        children: text,
                        props
                    };
                }
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'detail.colums.productCategoryName',
                    defaultMessage: '车型名称'
                }),
                dataIndex: 'productCategoryName',
                render: (text, record, index) => {
                    const props = {};
                    if(index === record.startIndex)
                        props.rowSpan = record.rowSpan;
                    else
                        props.rowSpan = 0;
                    return {
                        children: text,
                        props
                    };
                }
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'detail.column.partWarrantyCategoryCode',
                    defaultMessage: '备件索赔分类编号'
                }),
                dataIndex: 'partWarrantyCategoryCode',
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'detail.column.partWarrantyCategoryName',
                    defaultMessage: '备件索赔分类名称'
                }),
                dataIndex: 'partWarrantyCategoryName',
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'detail.column.remark',
                    defaultMessage: '备注'
                }),
                dataIndex: 'remark',
            }
        ];

        const tabs = data.map(item => {
            const {vehicleCategoryItems = EMPTY_ARRAY, vehicleItems = EMPTY_ARRAY, id, type, tabName} = item;
            const vehicleColumns = type === warrantyPolicyType.标准 ? categoryColumns : vinColumns;
            const dataSource = type === warrantyPolicyType.标准 ? vehicleCategoryItems : vehicleItems;
            return (
                <TabPane key={id} tab={tabName}>
                    <React.Fragment>
                        <DescriptionList size="large" className={styles.marginBottom}>
                            <Description
                                term={this.props.intl.formatMessage({
                                    id: 'detail.info.type',
                                    defaultMessage: '索赔类型'
                                })}>
                                {conventEnumValueToString(warrantyPolicyType, type)}
                            </Description>
                            <Description
                                term={this.props.intl.formatMessage({
                                    id: 'detail.info.warrantyMileage',
                                    defaultMessage: '索赔里程'
                                })}>
                                {item.warrantyMileage}
                            </Description>
                            <Description
                                term={this.props.intl.formatMessage({
                                    id: 'detail.info.warrantyDuration',
                                    defaultMessage: '索赔时间（月）'
                                })}>
                                {item.warrantyDuration}
                            </Description>
                        </DescriptionList>
                        <DescriptionList col={1} size="large">
                            <Description term={this.props.intl.formatMessage({
                                id: 'detail.info.remark',
                                defaultMessage: '备注'
                            })}>{item.remark}</Description>
                        </DescriptionList>
                    </React.Fragment>
                    <Divider />
                    <Collapse defaultActiveKey={['1']}>
                        <Panel header={this.props.intl.formatMessage({
                            id: 'detail.vehicles.title',
                            defaultMessage: '车型车辆清单'
                        })} key="1">
                            <Table
                                className="white-space-nowrap"
                                rowKey="rowKey"
                                columns={vehicleColumns}
                                pagination={false}
                                dataSource={dataSource}
                                {...TABLE} />
                        </Panel>
                    </Collapse>
                </TabPane>
            );
        });
        return tabs;
    }
    render() {
        const {details = EMPTY_ARRAY, options = EMPTY_ARRAY} = this.props.detail;
        const operations = [];
        if(hasPermissions(this.props.permissions, PERMISSION.enable) && hasPermissions(options, PERMISSION.enable))
            operations.push(
                <WrappedPopconfirm
                    id="enable"
                    key="enable"
                    title={this.props.intl.formatMessage({
                        id: 'detail.popconfirm.message',
                        defaultMessage: '是否继续?'
                    })}
                    okText={this.props.intl.formatMessage({
                        id: 'detail.popconfirm.confirm',
                        defaultMessage: '确认'
                    })}
                    cancelText={this.props.intl.formatMessage({
                        id: 'detail.popconfirm.cancel',
                        defaultMessage: '取消'
                    })}
                    onConfirm={this.handleEnableClick}>
                    <Button size="small">
                        {this.props.intl.formatMessage({
                            id: 'detail.popconfirm.enable',
                            defaultMessage: '生效'
                        })}
                    </Button>
                </WrappedPopconfirm>
            );
        if(hasPermissions(this.props.permissions, PERMISSION.update) && hasPermissions(options, PERMISSION.update))
            operations.push(
                <Button key="update" href={`#${routes.update.format(this.props.id)}`} size="small">
                    {this.props.intl.formatMessage({
                        id: 'detail.btn.update',
                        defaultMessage: '编辑'
                    })}
                </Button>
            );
        if(hasPermissions(this.props.permissions, PERMISSION.abandon) && hasPermissions(options, PERMISSION.abandon))
            operations.push(
                <WrappedPopconfirm
                    id="abandon"
                    key="abandon"
                    title={this.props.intl.formatMessage({
                        id: 'detail.popconfirm.message',
                        defaultMessage: '是否继续?'
                    })}
                    okText={this.props.intl.formatMessage({
                        id: 'detail.popconfirm.confirm',
                        defaultMessage: '确认'
                    })}
                    cancelText={this.props.intl.formatMessage({
                        id: 'detail.popconfirm.cancel',
                        defaultMessage: '取消'
                    })}
                    onConfirm={this.handleAbandonClick}>
                    <Button size="small">
                        {this.props.intl.formatMessage({
                            id: 'detail.btn.abandon',
                            defaultMessage: '作废'
                        })}
                    </Button>
                </WrappedPopconfirm>
            );
        const tabs = this.renderTabs(details);
        return (
            <div className={styles.detail}>
                <Spin spinning={this.props.loading || this.state.loading}>
                    <Card>
                        <DescriptionList size="large" className={styles.marginBottom} title={<Row><Col span={6}>{this.props.intl.formatMessage({
                            id: 'detail.dealerInfo.title',
                            defaultMessage: '政策信息'
                        })}</Col>
                        <Col className={styles.optionBtn} span={18}>{operations}</Col></Row>}>
                            <Description
                                term={this.props.intl.formatMessage({
                                    id: 'detail.info.brandCode',
                                    defaultMessage: '品牌编号'
                                })}>
                                {this.props.detail.brandCode}
                            </Description>
                            <Description
                                term={this.props.intl.formatMessage({
                                    id: 'detail.info.code',
                                    defaultMessage: '编号'
                                })}>
                                {this.props.detail.code}
                            </Description>
                            <Description
                                term={this.props.intl.formatMessage({
                                    id: 'detail.info.name',
                                    defaultMessage: '名称'
                                })}>
                                {this.props.detail.name}
                            </Description>
                            <Description
                                term={this.props.intl.formatMessage({
                                    id: 'detail.info.dealer',
                                    defaultMessage: '总代'
                                })}>
                                {`(${this.props.detail.dealerCode})${this.props.detail.dealerName}`}
                            </Description>
                            <Description
                                term={this.props.intl.formatMessage({
                                    id: 'detail.info.startDate',
                                    defaultMessage: '启用日期'
                                })}>
                                {formatDateTime(this.props.detail.startDate, DATE_FORMAT)}
                            </Description><Description
                                term={this.props.intl.formatMessage({
                                    id: 'detail.info.status',
                                    defaultMessage: '状态'
                                })}>
                                {conventEnumValueToString(warrantyPolicyStatus, this.props.detail.status)}
                            </Description>
                            <Description
                                term={this.props.intl.formatMessage({
                                    id: 'detail.info.creatorName',
                                    defaultMessage: '创建人'
                                })}>
                                {this.props.detail.creatorName}
                            </Description>
                            <Description
                                term={this.props.intl.formatMessage({
                                    id: 'detail.info.createTime',
                                    defaultMessage: '创建时间'
                                })}>
                                {formatDateTime(
                                    this.props.detail.createTime,
                                    DATETIME_FORMAT
                                )}
                            </Description>
                            <Description
                                term={this.props.intl.formatMessage({
                                    id: 'detail.info.modifierName',
                                    defaultMessage: '修改人'
                                })}>
                                {this.props.detail.modifierName}
                            </Description>
                            <Description
                                term={this.props.intl.formatMessage({
                                    id: 'detail.info.modifyTime',
                                    defaultMessage: '修改时间'
                                })}>
                                {formatDateTime(
                                    this.props.detail.modifyTime,
                                    DATETIME_FORMAT
                                )}
                            </Description>
                            <Description
                                term={this.props.intl.formatMessage({
                                    id: 'detail.info.abandonerName',
                                    defaultMessage: '作废人'
                                })}>
                                {this.props.detail.abandonerName}
                            </Description>
                            <Description
                                term={this.props.intl.formatMessage({
                                    id: 'detail.info.abandonTime',
                                    defaultMessage: '作废时间'
                                })}>
                                {formatDateTime(
                                    this.props.detail.abandonTime,
                                    DATETIME_FORMAT
                                )}
                            </Description>
                        </DescriptionList>
                        <DescriptionList col={1} size="large">
                            <Description term={this.props.intl.formatMessage({
                                id: 'detail.info.remark',
                                defaultMessage: '备注'
                            })}>{this.props.detail.remark}</Description>
                        </DescriptionList>
                    </Card>
                    <Card title={this.props.intl.formatMessage({
                        id: 'detail.detail.title',
                        defaultMessage: '条款信息'
                    })}>
                        <Tabs>
                            {tabs}
                        </Tabs>
                    </Card>
                </Spin>
                <div className="page-toolbar">
                    <Button type="primary" disabled={this.props.loading} onClick={this.props.onCancel}>
                        {this.props.intl.formatMessage({
                            id: 'detail.btn.retrun',
                            defaultMessage: '返回'
                        })}
                    </Button>
                </div>
            </div>
        );
    }
}
Detail.propTypes = {
    detail: PropTypes.object.isRequired,
    id: PropTypes.string.isRequired,
    init: PropTypes.func.isRequired,
    loading: PropTypes.bool.isRequired,
    permissions: PropTypes.array.isRequired,
    onCancel: PropTypes.func.isRequired,
    onClickAbandon: PropTypes.func.isRequired,
    onClickEnable: PropTypes.func.isRequired,
    onUmount: PropTypes.func.isRequired,
    intl: PropTypes.object
};
import {connect} from 'react-redux';
import {createSelector} from 'reselect';
import {getOrderDetail, clearData, onClickAbandonForDetail, onClickEnableForDetail, tableSearch} from './actions';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const getDetailData = selectorFactory(['page', 'domainData', 'orderDetail', 'data']);
const getCondition = createSelector(
    state => getDetailData(state),
    data => {
        const {details = [], ...obj} = data;
        const indexObj = {};
        const newDetails = details.map(item => {
            if(indexObj[item.type])
                indexObj[item.type] += 1;
            else
                indexObj[item.type] = 1;
            const tabName = `${conventEnumValueToString(warrantyPolicyType, item.type)}${indexObj[item.type]}`;
            const {vehicleCategoryItems = EMPTY_ARRAY, vehicleItems = EMPTY_ARRAY, ...props} = item;
            let count = 0;
            const newCategories = [];
            const newVehicles = [];
            vehicleCategoryItems.forEach(v => {
                const {partWarrantyCategories = EMPTY_ARRAY, ...vprops} = v;
                const startIndex = count;
                const rowSpan = partWarrantyCategories.length;
                count += partWarrantyCategories.length;
                const categories = partWarrantyCategories.map(p => ({
                    rowKey: uuid(),
                    partWarrantyCategoryId: p.id,
                    partWarrantyCategoryCode: p.code,
                    partWarrantyCategoryName: p.name,
                    remark: p.remark,
                    startIndex,
                    rowSpan,
                    ...vprops
                }));
                newCategories.push(...categories);
            });
            vehicleItems.forEach(v => {
                const {parts = EMPTY_ARRAY, ...vprops} = v;
                const startIndex = count;
                const rowSpan = parts.length;
                count += parts.length;
                const vehicles = parts.map(p => ({
                    rowKey: uuid(),
                    partId: p.id,
                    partCode: p.code,
                    partName: p.name,
                    remark: p.remark,
                    startIndex,
                    rowSpan,
                    ...vprops
                }));
                newVehicles.push(...vehicles);
            });
            return {
                ...props,
                tabName,
                vehicleCategoryItems: newCategories,
                vehicleItems: newVehicles
            };
        });
        return {
            ...obj,
            details: newDetails
        };
    }
);
const mapStateToProps = (state, ownProps) => ({
    id: ownProps.id,
    loading: state.getIn(['page', 'domainData', 'orderDetail', 'isFetching']),
    detail: getCondition(state),
    permissions: getPermissions(state),
});

const mapDispatchToProps = (dispatch, ownProps) => ({
    init: () => dispatch(getOrderDetail(ownProps.id)),
    onCancel: () => {
        ownProps.history.goBack();
    },
    onClickAbandon: () =>
        dispatch(onClickAbandonForDetail(ownProps.id)).then(res => {
            if(res.ok) {
                dispatch(tableSearch({
                    pageIndex: PAGE.index
                }));
                ownProps.history.push(routes.query.url());
            }
            return res.ok;
        }),
    onClickEnable: () =>
        dispatch(onClickEnableForDetail(ownProps.id)).then(success => {
            if(success) {
                dispatch(tableSearch({
                    pageIndex: PAGE.index
                }));
                ownProps.history.push(routes.query.url());
            }
            return success;
        }),
    onUmount: () => dispatch(clearData()),
});

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(injectIntl(Detail));

